﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TPA.DataAccess;
using System.Reflection;
using TVProgramAnalyst.Helper;

namespace TVProgramAnalyst.TimeLine
{
    public partial class frmTimelineExplorer : Form
    {
        public frmTimelineExplorer()
        {
            InitializeComponent();
        }

        IEnumerable<TPA.DataAccess.vwTimelineSegment> _SrcTimeline;
        PropertyInfo[] pis = typeof(TPA.DataAccess.vwTimelineSegment).GetProperties();

        private void frmTimelineExplorer_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            //BrowseByDate();
            BrowseByChannel();
            this.reportViewer1.RefreshReport();
            this.reportViewer1.RefreshReport();
            splitContainerBottom.SplitterDistance = splitContainerMain.SplitterDistance;
        }

        

        private void tvBrowser_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            switch(e.Node.Tag.ToString()) 
            {
                case "channel_data":
                    _SrcTimeline = BLLFactory.TimeLineBLL.GetTimelineSegment(DateTime.Parse(e.Node.Parent.Text), e.Node.Text);
                    dgvTimeline.DataSource = _SrcTimeline;
                    dgvTimeline.Columns[0].Visible = false;
                    tVProgamAnalyticEntities1BindingSource.DataSource = BLLFactory.TimeLineBLL.GetTimelineSegment(DateTime.Parse(e.Node.Parent.Text), e.Node.Text);
                    this.reportViewer1.RefreshReport();
                    this.Text = "时间线浏览器 - " + e.Node.Text + " - " + e.Node.Parent.Text;
                    break;
                case "date_data":
                    _SrcTimeline = BLLFactory.TimeLineBLL.GetTimelineSegment(DateTime.Parse(e.Node.Text), e.Node.Parent.Parent.Text);
                    dgvTimeline.DataSource = _SrcTimeline;
                    dgvTimeline.Columns[0].Visible = false;
                    tVProgamAnalyticEntities1BindingSource.DataSource = BLLFactory.TimeLineBLL.GetTimelineSegment(DateTime.Parse(e.Node.Text), e.Node.Parent.Parent.Text);
                    this.reportViewer1.RefreshReport();
                    this.Text = "时间线浏览器 - " + e.Node.Text + " - " + e.Node.Parent.Parent.Text;
                    break;
            }
            if (e.Node.Nodes.Count < 1 || e.Node.Nodes[0].Text == "Loading...")
            {
                Cursor = Cursors.WaitCursor;
                switch (e.Node.Tag.ToString())
                {
                    case "year1": //load month
                        e.Node.Nodes.Clear();
                        string[] months = BLLFactory.TimeLineBLL.GetMonthByYear(e.Node.Text);
                        foreach (string month in months)
                        {
                            TreeNode monthnode = e.Node.Nodes.Add(month);
                            monthnode.Tag = "month";
                            monthnode.Nodes.Add("Loading...");
                        }
                        break;
                    case "month": //load date
                        string[] dates = BLLFactory.TimeLineBLL.GetDayByYearAndMonth(e.Node.Parent.Text, e.Node.Text);
                        e.Node.Nodes.Clear();
                        foreach (string date in dates)
                        {
                            TreeNode datenode = e.Node.Nodes.Add(date);
                            datenode.Tag = "date";
                            datenode.Nodes.Add("Loading...");
                        }
                        break;
                    case "date":  //load channel
                        e.Node.Nodes.Clear();
                        string[] channels = BLLFactory.TimeLineBLL.GetChannel(e.Node.Text);
                        foreach (string channel in channels)
                        {
                            e.Node.Nodes.Add(channel).Tag = "channel_data";
                        }
                        break;
                    case "channel":// load years
                        e.Node.Nodes.Clear();
                        string[] years = BLLFactory.TimeLineBLL.GetYearInChannel(e.Node.Text);
                        foreach (string year in years)
                        {
                            //load dates of a specific channel in a specific year
                            TreeNode yearnode = e.Node.Nodes.Add(year);
                            yearnode.Tag = "year2";
                            yearnode.Nodes.Add("Loading...");
                        }
                        break;
                    case "year2"://load date
                        e.Node.Nodes.Clear();
                        string[] dates2 = BLLFactory.TimeLineBLL.GetDateInYearAndChannel(e.Node.Text, e.Node.Parent.Text);
                        foreach (string date in dates2)
                        {
                            e.Node.Nodes.Add(date).Tag = "date_data";
                        }
                        break;
                }
                Cursor = Cursors.Arrow;
            }
        }

        private void tvBrowser_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void tabpageBrowseByDate_Enter(object sender, EventArgs e)
        {
            //BrowseByDate();
        }

        private void tabpageBrowseByChannel_Enter(object sender, EventArgs e)
        {
            //BrowseByChannel();
        }

        private void BrowseByDate()
        {
            LoadTreeViewByDate();
            tabpageBrowseByDate.Controls.Add(tvBrowser);
            dgvTimeline.DataSource = null;
        }

        private void BrowseByChannel()
        {
            LoadTreeViewByChannel();
            tabpageBrowseByChannel.Controls.Add(tvBrowser);
            dgvTimeline.DataSource = null;
        }

        private void LoadTreeViewByDate()
        {
            //List<string> tvBrowser.Nodes=new List<string>();
            tvBrowser.Nodes.Clear();
            string[] years=BLLFactory.TimeLineBLL.GetYears();
            foreach (string year in years)
            {
                TreeNode yearnode= tvBrowser.Nodes.Add(year);
                yearnode.Tag = "year1";
                yearnode.Nodes.Add("Loading...");
            }
            tvBrowser.HideSelection = false;
        }

        private void LoadTreeViewByChannel()
        {
            tvBrowser.Nodes.Clear();
            //load channels
            string[] channels = BLLFactory.TimeLineBLL.GetChannel();
            foreach (string channel in channels)
            {
                //load years of a specific channel
                TreeNode channelnode = tvBrowser.Nodes.Add(channel);
                channelnode.Tag = "channel";
                channelnode.Nodes.Add("Loading...");
            }
        }

        private void tabpageBrowseByDate_Click(object sender, EventArgs e)
        {
            //BrowseByDate();
        }

        private void tabpageBrowseByChannel_Click(object sender, EventArgs e)
        {
            //BrowseByChannel();
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.ToolTipText)
            {
                case "Date":
                    BrowseByDate();
                    break;
                case "Channel":
                    BrowseByChannel();
                    break;
            }
                
        }

        private void btnSwitchView_Click(object sender, EventArgs e)
        {

        }

        private void btnSwitchView_CheckedChanged(object sender, EventArgs e)
        {
            if (btnSwitchView.Checked)
            {
                reportViewer1.Visible = true;
                dgvTimeline.Visible = false;
            }
            else
            {
                reportViewer1.Visible = false;
                dgvTimeline.Visible = true;
            }


        }

        private void toolStripBtnRefresh_Click(object sender, EventArgs e)
        {
            int index = tabControl1.SelectedIndex;
            tabControl1.SelectedIndex = 1;
            tabControl1.SelectedIndex = 0;
            tabControl1.SelectedIndex = index;

        }

        private void frmTimelineExplorer_Resize(object sender, EventArgs e)
        {

        }

        private void dgvTimeline_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            Program selectedProgram = BLLFactory.ProgramBLL.Get((Guid)dgvTimeline.Rows[e.RowIndex].Cells[0].Value);
            frmProgramEditor frm = new frmProgramEditor();
            frm.SetProgram(selectedProgram,SaveMode.Update);
            frm.ShowDialog(this);
            Program savedProgram=frm.Program;
            frm.Dispose();
            //MessageBox.Show(tvBrowser.SelectedNode.Text+";"+tvBrowser.SelectedNode.Tag.ToString());
            if (savedProgram != null)
            {
                dgvTimeline.Rows[e.RowIndex].Cells[1].Value = savedProgram.Name;
                dgvTimeline.Rows[e.RowIndex].Cells[9].Value = savedProgram.EnglishName;
                if (savedProgram.Subcategory != null)
                {
                    dgvTimeline.Rows[e.RowIndex].Cells[10].Value = savedProgram.Subcategory.Parent.Name;
                    dgvTimeline.Rows[e.RowIndex].Cells[11].Value = savedProgram.Subcategory.Name;
                    dgvTimeline.Rows[e.RowIndex].Cells[12].Value = savedProgram.Subcategory.EnglishName;
                    dgvTimeline.Rows[e.RowIndex].Cells[15].Value = savedProgram.Subcategory.Parent.EnglishName;
                }
            }
        }

        private void dgvTimeline_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        private void dgvTimeline_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Cursor = Cursors.WaitCursor;
            //tableTimelineDetails.Controls.Clear();
            //PropertyInfo[] pis = typeof(TPA.DataAccess.vwTimelineSegment).GetProperties();
            //foreach (PropertyInfo pi in pis)
            //{
            //    TPA.DataAccess.vwTimelineSegment obj = _SrcTimeline.ElementAt(e.RowIndex);
            //    string value = "";
            //    if (pi.GetValue(obj, null) != null)
            //        value = pi.GetValue(obj, null).ToString();
            //    tableTimelineDetails.Controls.Add(new Label() { Text = ReflectionHelper.getDisplayName(pi) + ": " + value, AutoSize = true });//
            //}
            TPA.DataAccess.vwTimelineSegment obj = _SrcTimeline.ElementAt(e.RowIndex);
            ShowTimeLineDetails(obj);
        }

        private void dgvTimeline_DataSourceChanged(object sender, EventArgs e)
        {
            lblTotalRecords.Text = dgvTimeline.Rows.Count.ToString();
            if (dgvTimeline.Rows.Count > 0)
            {
                Cursor = Cursors.WaitCursor;
                lblStartTime.Text = dgvTimeline.Rows[0].Cells[4].Value.ToString();
                lblEndTime.Text = dgvTimeline.Rows[dgvTimeline.Rows.Count - 1].Cells[4].Value.ToString();
                TPA.DataAccess.vwTimelineSegment obj = _SrcTimeline.ElementAt(0);
                Cursor = Cursors.Arrow;
                ShowTimeLineDetails(obj);
            }
        }

        void ShowTimeLineDetails(TPA.DataAccess.vwTimelineSegment obj)
        {
            Cursor = Cursors.WaitCursor; 
            tableTimelineDetails.Controls.Clear();
            
            foreach (PropertyInfo pi in pis)
            {
                string value = "";
                if (pi.GetValue(obj, null) != null)
                    value = pi.GetValue(obj, null).ToString();
                tableTimelineDetails.Controls.Add(new Label() { Text = ReflectionHelper.getDisplayName(pi) + ": " + value, AutoSize = true });
            }
            Cursor = Cursors.Arrow;
        }

        private void splitContainer2_SplitterMoving(object sender, SplitterCancelEventArgs e)
        {
            
        }

        private void splitContainer2_SplitterMoved(object sender, SplitterEventArgs e)
        {
                splitContainerBottom.SplitterDistance = e.SplitX;
        }

        private void splitContainer2_Resize(object sender, EventArgs e)
        {
            splitContainerBottom.SplitterDistance = splitContainerMain.SplitterDistance;
        }
    }
}
